default_platform :ios

platform :ios do
  desc "Release iOS app to TestFlight"
  lane :release_ios_testflight do
    # Create GoogleService-Info.plist from GitHub secret
    File.write(
      File.join(Dir.pwd, "../GoogleService-Info.plist"),
      ENV["GOOGLE_SERVICES_PLIST"]
    )
    
    setup_ci(force: true)

    api_key = app_store_connect_api_key(
      key_id: ENV['APP_STORE_CONNECT_API_KEY_ID'],
      issuer_id: ENV['APP_STORE_CONNECT_API_ISSUER_ID'],
      key_content: ENV['APP_STORE_CONNECT_API_KEY_CONTENT'].gsub('\\n', "\n"),
      in_house: false
    )

    # Helper method to encode GitHub token
    def encoded_github_token
      require 'base64'
      Base64.strict_encode64("x-access-token:#{ENV['MATCH_GITHUB_TOKEN']}")
    end

    match(
      type: "development",
      readonly: true,
      api_key: api_key,
      git_branch: "master",
      git_basic_authorization: encoded_github_token
    )

    match(
      type: "appstore",
      readonly: true,
      api_key: api_key,
      git_branch: "master",
      #password: ENV['MATCH_PASSWORD'], # will be picked up from environment variables
      git_basic_authorization: encoded_github_token
    )

    build_ios_app(
      scheme: "PocketPal",
      export_method: "app-store",
      output_directory: "./build",
      clean: true,
      export_options: {
        provisioningProfiles: {
          "ai.pocketpal" => "match AppStore ai.pocketpal"
        },
        signingStyle: "manual"
      }
    )

    upload_to_testflight(
      api_key: api_key,
      skip_waiting_for_build_processing: false,
      wait_processing_interval: 60, # Check every minute
      wait_for_uploaded_build: true,
      wait_processing_timeout_duration: 1800 # 30 minutes timeout
    )
  end
end
